package com.gxc.integer;

import java.util.Arrays;

/**
 * 62. 不同路径

 一个机器人位于一个 m x n 网格的左上角 （起始点在下图中标记为 “Start” ）。

 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角（在下图中标记为 “Finish” ）。

 问总共有多少条不同的路径？
 */
public class UniquePaths {

    public static void main(String[] args) {
        System.out.println(handle(51,9));
        System.out.println(handle2(51,9));
        System.out.println(handle3(51,9));
    }

    public static int handle(int m, int n) {
        int a = 1;
        int sum = m + n - 2;
        int min = Math.min(m, n);
        for (int i = 0; i < min-1; i++) {
            if (a > Integer.MAX_VALUE / (sum - i)) a = a  / (i+1) * (sum - i);
            else a = a * (sum - i) / (i+1) ;
        }

        return a;
    }

    /**
     * dp[i][j] = dp[i-1][j] + dp[i][j-1]
     * @param m
     * @param n
     * @return
     */
    public static int handle2(int m, int n) {
        int[][] dp = new int[m][n];
        //dp[i][0]=1;
        for (int i = 0; i < dp.length; i++) {
            dp[i][0]=1;
        }
        //dp[0][j]=1
        Arrays.fill(dp[0], 1);
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[i].length; j++) {
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }

    /**
     * dp[i][j] = dp[i-1][j] + dp[j][i-1];
     * dp 只依赖 左边和上边。可以优化为单行数组
     * @param m
     * @param n
     * @return
     */
    public static int handle3(int m, int n) {
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] = dp[j-1] + dp[j];
            }
        }
        return dp[n-1];
    }

    class Solution {
        public int uniquePaths(int m, int n) {
            int[][] f = new int[m][n];
            for (int i = 0; i < m; ++i) {
                f[i][0] = 1;
            }
            for (int j = 0; j < n; ++j) {
                f[0][j] = 1;
            }
            for (int i = 1; i < m; ++i) {
                for (int j = 1; j < n; ++j) {
                    f[i][j] = f[i - 1][j] + f[i][j - 1];
                }
            }
            return f[m - 1][n - 1];
        }
    }

    class Solution2 {
        public int uniquePaths(int m, int n) {
            int[] f = new int[n];
            for (int i = 0; i < n; ++i) {
                f[i] = 1;
            }
            for (int i = 1; i < m; ++i) {
                for (int j = 1; j < n; ++j) {
                    f[j] += f[j - 1];
                }
            }
            return f[n - 1];
        }
    }


}
